﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Lon.Util;
using Lon.Data;
using System.Collections;
using LonLog;

//using DBLib;

namespace Lon.Server
{
    public partial class MainForm : Form
    {
        #region 字符串常量
        //Application
        public const string ID_APP_TEXT = "应用服务器";

        //Button
        public const string ID_CLEAR = "清空";
        public const string ID_PAUSE = "暂停";
        public const string ID_CONTINUE = "继续";

        //NetList
        public const string ID_ID = "序号";
        public const string ID_DBM = "电报码";
        public const string ID_NETNODE = "节点";
        public const string ID_IP = "IP地址";
        public const string ID_PORT = "连接状态";
        public const string ID_NAME = "名称";
        public const string ID_UPDATE_TIME = "更新时间";
        public const string ID_CONNECT_STATION = "连接站机";

        //ViewData
        public const string ID_TIME = "时间";
        public const string ID_TYPE = "类型";
        public const string ID_MESSAGE = "消息";
      
        #endregion

    

        public string BuildDate
        {
            get
            {
                //return "2013/5/16";
                return "2014/8/18";
            }
        }

        public string AssemblyVersion
        {
            get
            {
                return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        AppServer server;
        public MainForm(AppServer server)
        {
            InitializeComponent();
            this.server = server;
        }
        
        protected override void OnLoad(EventArgs e)
        {
            this.Text = ID_APP_TEXT;
            this.notifyIcon1.Text = ID_APP_TEXT;
            this.btnClear.Text = ID_CLEAR;
            this.btnPause.Text = ID_PAUSE;
            InitDataGrid();
            Start();
            base.OnLoad(e);
            splitContainer2.Panel2Collapsed = true;
            LonLog.LogHelper.LogEventHandler += new EventHandler<LonLog.LogMessageArgs>(LogHelper_LogEventHandler);
            
        }

        Queue<LonLog.LogMessageArgs> messageQueue = new Queue<LonLog.LogMessageArgs>(); 

        void LogHelper_LogEventHandler(object sender, LonLog.LogMessageArgs e)
        {
            if (pause) return;
            messageQueue.Enqueue(e);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            bool canExit = false;
            if (MessageBox.Show(" 是否退出?   ", "退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //--------------------------------
                DateTime endTime = DateTime.Now;
                canExit = true;
            }

            e.Cancel = !canExit;
            base.OnFormClosing(e);
           
        }

        #region 最小化
        bool canClose = false;
        protected override void WndProc(ref   Message m)
        {
            //关闭后最小化到任务栏
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_CLOSE = 0xF060;
            if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
            {
                if (!canClose) WindowMinimized();
                return;
            }
            base.WndProc(ref m);
        }

        private void WindowMinimized()
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            //notifyIcon1.ShowBalloonTip(1000, ID_APP_TEXT, string.Format("{0}已最小化", ID_APP_TEXT), ToolTipIcon.Info);
        }

        private void WindowsRestore()
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
             Win32Api.SetForegroundWindow(this.Handle);
             Win32Api.OpenIcon(this.Handle);  
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) WindowsRestore();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            WindowsRestore();
        }


        private void pmnuShow_Click(object sender, EventArgs e)
        {
            WindowsRestore();
        }

        #endregion

   

        void Start()
        {
          
            DiagnoForm.DiagnoList.Add(string.Format("{0} 系统数据初始化正常!", this.Text));

            DefaultPrivilegeView();

          
            //statusLabel1.Text = string.Format("前置服务器[{0}]已启动！ 监听端口:{1}", frontServer.Dbm, frontServer.Port);
            statusLabel1.Text = string.Format("{0} [{1}]已启动！ 监听端口:{2}", this.Text,  server.Dbm, server.Port);
          
            DiagnoForm.DiagnoList.Add(string.Format("{0} 启动正常！", this.Text));
          
        


        }

        bool preConnStatus = false;
        void UpdateNetView()
        {
            try
            {
              
                  
        
                
                    //---------------------------------------------------------

                    //更新或添加项  
                    bool exist = false;
                    List<NetNode> nodes = server.NetNodeManager.GetNodeList();
                  
                    foreach (NetNode item in nodes)
                    {
                       
                        exist = false;

                        foreach (DataRow row in dtNetList.Rows)
                        {
                            string dbm = row[ID_DBM].ToString();

                            if (dbm == item.Dbm)
                            {
                                //更新
                                row[ID_IP] = String.IsNullOrEmpty(item.Ip)?"":item.Ip;
                        
                                row[ID_PORT] = item.ConnectedState?"正常":"未连接";
                                row[ID_NAME] = String.IsNullOrEmpty(item.Name) ? "" : item.Name;//EnumHelper.GetEnumDisString(item.NodeType.GetType(),(int)item.NodeType);
                                row[ID_UPDATE_TIME] = item.LastStateTime;
                                row[ID_NETNODE] = item;
                                StringBuilder sb = new StringBuilder();
                               
                              
                                exist = true;
                                break;
                            }
                        }

                        if (!exist)
                        {
                            DataRow row = dtNetList.NewRow();
                            row[ID_DBM] = item.Dbm;
                            row[ID_IP] = item.Ip;
                            row[ID_PORT] = item.ConnectedState?"正常":"";
                            row[ID_NAME] = String.IsNullOrEmpty(item.Name) ? "" : item.Name; //EnumHelper.GetEnumDisString(item.NodeType.GetType(), (int)item.NodeType);
                            row[ID_UPDATE_TIME] = item.LastStateTime.ToString("HH:mm:ss");
                            row[ID_NETNODE] = item;
                            dtNetList.Rows.Add(row);
                        }

                    }

                    //删除不存在的项
                    for (int j = 0; j < dtNetList.Rows.Count; j++)
                    {
                        DataRow row = dtNetList.Rows[j];
                        string dbm = row[ID_DBM].ToString();
                        var node = row[ID_NETNODE] as NetNode;
                        if(node.ConnectedState==false)
                        {

                        }
                        exist = false;
                        foreach (var item in nodes)
                        {
                            if (dbm == item.Dbm)
                            {
                                exist = true;
                                break;
                            }
                        }
                    }

                    //---------------------------------------------------------
                    for (int j = 0; j < dtNetList.Rows.Count; j++)
                    {
                        DataRow row = dtNetList.Rows[j];
                        row[ID_ID] = (j + 1).ToString();
                    }

               
            }
            catch(Exception ex)
            {
                LonLog.LogHelper.WriteLog("MainForm", LogType.Error, ex.Message.ToString() + "\r\n" + ex.StackTrace.ToString());
            }

        }

     
        
    
   

        private void btnClear_Click(object sender, EventArgs e)
        {
            dtViewData.Rows.Clear();
            txtDetail.Clear();
        }

        bool pause = false;
        private void btnPause_Click(object sender, EventArgs e)
        {
            pause = !pause;
            Button curButton = (Button)sender;
            if (pause)
                curButton.Text = ID_CONTINUE;            
            else
                curButton.Text = ID_PAUSE;
        }

     
        private void cboNodeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string text = cboNodeType.Text.Trim();
            if (text == "全部显示") text = "";

            filterNetList.Set(ID_NAME, text);
            bsNetList.Filter = filterNetList.GetText();
        }

        #region 表格及过滤器
        DataTable dtViewData = new DataTable();
        BindingSource bsViewData = new BindingSource();
        DataFilter filterViewData;

        DataTable dtNetList = new DataTable();
        BindingSource bsNetList = new BindingSource();
        DataFilter filterNetList;

        



        void InitDataGrid()
        {
            SetTagValue();

            //------------------------------------------

            filterNetList = new DataFilter();

            dtNetList.Columns.Clear();
            dtNetList.Columns.Add(ID_ID);
            dtNetList.Columns.Add(ID_DBM);
            dtNetList.Columns.Add(ID_IP);
            dtNetList.Columns.Add(ID_PORT);
            dtNetList.Columns.Add(ID_NAME);
            dtNetList.Columns.Add(ID_UPDATE_TIME);
            dtNetList.Columns.Add(ID_CONNECT_STATION);
            dtNetList.Columns.Add(ID_NETNODE, typeof(NetNode));

            bsNetList.DataSource = dtNetList;

            dataGridView1.DataSource = bsNetList;
            dataGridView1.Columns[dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns[ID_NETNODE].Visible = false;
            //------------------------------------------

            filterViewData = new DataFilter();

            dtViewData.Columns.Clear();
            dtViewData.Columns.Add(ID_TIME);
            dtViewData.Columns.Add(ID_TYPE);
            dtViewData.Columns.Add(ID_MESSAGE);
            bsViewData.DataSource = dtViewData;
            dataGridView2.DataSource = bsViewData;
            dataGridView2.Columns[ID_TIME].Width = 140;
            dataGridView2.Columns[ID_TYPE].Width = 70;
            dataGridView2.Columns[dataGridView2.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
          

        }

        void SetTagValue()
        {
            txtID.Tag = ID_ID;
            txtDBM.Tag = ID_DBM;
            txtIP.Tag = ID_IP;
            txtPORT.Tag = ID_PORT;

            txtDest.Tag = ID_TYPE;
         
                
        }

        void NetList_TextChanged(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            string text = textBox.Text;
            string key = textBox.Tag.ToString();

            filterNetList.Set(key, text);
            bsNetList.Filter = filterNetList.GetText();
        }

        void ViewData_TextChanged(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            string text = textBox.Text;
            string key = textBox.Tag.ToString();

            filterViewData.Set(key, text);
            bsViewData.Filter = filterViewData.GetText();
        }

        #endregion

  
        /// <summary>
        /// 当前查看的数据节点
        /// </summary>
    
 
        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //客户端列表
            DataGridView dgv = (DataGridView)sender;
            if (dgv.Rows.Count > 0 && e.RowIndex < dgv.Rows.Count)
            {
                DataGridViewRow row = dgv.Rows[e.RowIndex];
                string dbm = row.Cells[ID_DBM].Value.ToString();
                string ip = row.Cells[ID_IP].Value.ToString();
                string port = row.Cells[ID_PORT].Value.ToString();
             
                if (string.IsNullOrEmpty(dbm)) return;
             
                var node = row.Cells[ID_NETNODE].Value as NetNode;
                if (node == null)
                {
                    return;
                }
                FormDataShowNew form = new FormDataShowNew(node);
                form.Show(this);
                 
            }

        }




    

        void DefaultPrivilegeView()
        {
            //默认权限状态
            mnuConfigEdit.Enabled = false;
            mnuUserMan.Enabled = false;
            mnuLogError.Enabled = false;
            mnuLogInfo.Enabled = false;
            mnuUserLog.Enabled = false;
            mnuSaveIPList.Enabled = false;
            mnuDiagnoSystem.Enabled = false;
            mnuExit.Enabled = true;
            pmnuExit.Enabled = mnuExit.Enabled;

            statusLabel3.Text = LoginMan.Instance.LoginUser;

            if (CheckHaveNotUser())
            {
                //如果用户名为空，提醒创建管理员账号
                mnuUserMan.Enabled = true;
                mnuExit.Enabled = true;
                pmnuExit.Enabled = mnuExit.Enabled;

                if (MessageBox.Show(" 账号为空，请建立管理员账号，是否开始创建用户？   ", "创建账号", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {                  
                    mnuUserMan.PerformClick();
                }
            }
            
        }

        private bool CheckHaveNotUser()
        {
            return false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateNetView();
            UpdateViewData();
        }
        void UpdateViewData()
        {
            try
            {
                if (pause) return;
               
                LonLog.LogMessageArgs[] recs = null;
                lock (messageQueue)
                {
                    recs = messageQueue.ToArray();
                    messageQueue.Clear();
                }
                if (recs == null || recs.Length == 0)
                {
                    return;
                }
                ShowRawData(recs);



            }
            catch (Exception ex)
            {
            }
        }

        private void ShowRawData(LonLog.LogMessageArgs[] recs)
        {
            for (int i = 0; i < recs.Length; i++)
            {
                var item = recs[i];
                DataRow row = dtViewData.NewRow();
                row[ID_TIME] = item.Time.ToString("HH:mm:ss.fff");
                row[ID_TYPE] = EnumHelper.GetEnumDisString(item.LogType.GetType(), (int)item.LogType);
                row[ID_MESSAGE] = item.Message;

                dtViewData.Rows.Add(row);

                //dtViewData.Rows.InsertAt(row, 0);  
                if (dtViewData.Rows.Count > 2000)
                {
                    dtViewData.Rows.RemoveAt(0);
                }
            }

        }
        private void splitContainer2_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

     

     





    }
}
